package com.zhenyi.toupiao.index;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;

import com.cenjiawen.common.IndexController;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.toupiao.common.model.TpActivity;
import com.toupiao.common.model.TpActivityVote;
import com.toupiao.common.model.TpJoin;
import com.toupiao.common.model.TpOrder;
import com.toupiao.common.model.TpUserVote;
import com.wxpay.utils.MD5Util;
import com.zhenyi.toupiao.core.Encrypt;

import cn.hutool.core.codec.Base64;

public class BillController extends IndexController {

	protected final String PARTNER_KEY = PropKit.get("TP_PARTNER_KEY");

	private Map<String, String> getDeResult(String en) {
		String key = MD5Util.MD5Encode(PARTNER_KEY, "utf-8");
		String de = Encrypt.Aes256Decode(Base64.decode(en), key.getBytes());
		Map<String, String> result = PaymentKit.xmlToMap(de);
		return result;
	}

	@Clear
	@Before(Tx.class)
	public void billPush() {
		// try {
		String xmlResult = HttpKit.readData(getRequest());
		if (StrKit.isBlank(xmlResult)) {
			renderPayFail();
			return;
		}
		// if (DEBUG) {
		// LogKit.info(xmlResult);
		// }
		Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
		// String appid = result.get("appid");
		String bank_type = result.get("bank_type");
		String cash_fee = result.get("cash_fee");
		String fee_type = result.get("fee_type");
		String is_subscribe = result.get("is_subscribe");
		// String mch_id = result.get("mch_id");
		// String nonce_str = result.get("nonce_str");
		// String openid = result.get("openid");
		String out_trade_no = result.get("out_trade_no");
		String result_code = result.get("result_code");
		String return_code = result.get("return_code");
		String sign = result.get("sign");
		String time_end = result.get("time_end");
		String total_fee = result.get("total_fee");
		String trade_type = result.get("trade_type");
		String transaction_id = result.get("transaction_id");
		String attach = result.get("attach");
		if (!"SUCCESS".equals(return_code)) {
			LogKit.warn("返回失败 " + out_trade_no);
			renderPaySuccess();
			return;
		}
		if (!"SUCCESS".equals(result_code)) {
			LogKit.warn("支付结果失败 " + out_trade_no);
			renderPaySuccess();
			return;
		}
		System.out.println(JsonKit.toJson(result));
		// System.out.println("--------");
		// System.out.println(JsonKit.toJson(result));
		// System.out.println("out_trade_no: " + out_trade_no);
		// System.out.println("total_fee: " + total_fee);
		// System.out.println("cash_fee: " + cash_fee);
		// System.out.println("out_trade_no: " + out_trade_no);
		// System.out.println("--------");

		String partnerKey = PARTNER_KEY;
		String mySign = PaymentKit.createSign(result, partnerKey);
		if (!mySign.equals(sign)) {
			// order.setVerify(1);
			LogKit.warn("Sign失败 " + out_trade_no);
			renderPayFail();
			return;
		} else {
			// order.setVerify(0);
		}
		onPaySuccess(out_trade_no);
		renderPaySuccess();
	}

	private void renderPayFail() {
		String returnXML = "<xml>\n" + "<return_code><![CDATA[FAIL]]></return_code>\n"
				+ "<return_msg><![CDATA[FAIL]]></return_msg>\n" + "</xml>";
		renderText(returnXML, "text/xml");
	}

	private void renderPaySuccess() {
		String returnXML = "<xml>\n" + "<return_code><![CDATA[SUCCESS]]></return_code>\n"
				+ "<return_msg><![CDATA[OK]]></return_msg>\n" + "</xml>";
		renderText(returnXML, "text/xml");
	}

	private void onPaySuccess(String orderNo) {
		boolean flag = Db.tx(new IAtom() {
			
			@Override
			public boolean run() throws SQLException {
				TpOrder order = TpOrder.dao.searchFirst("orderNo", orderNo);
				TpUserVote userVote = new TpUserVote();
				userVote.setJoinId(order.getJoinId().longValue());
				userVote.setUserId(order.getUserId());
				userVote.save();
				
				TpJoin join = TpJoin.dao.findById(order.getJoinId());
				TpActivity activity = TpActivity.dao.findById(join.getActivityId());
				TpActivityVote activityVote = TpActivityVote.dao.findById(order.getActivityVoteId());
				join.setVote(join.getVote() + (activityVote.getVote() * activity.getVotePerDiamond()));
				join.update();

				// 更新活动投票统计
				SqlPara sqlPara = Db.use("toupiao").getSqlPara("TPFindActicityJoin", activity.getId());
				List<TpJoin> list = TpJoin.dao.find(sqlPara);
				int count = 0;
				for (TpJoin item : list) {
					count += item.getVote();
				}
				activity.setVoteCount(count);
				activity.update();
				
				SqlPara sqlPara2 = Db.use("toupiao").getSqlPara("TPFindRank", activity.getId());
				List<TpJoin> items = TpJoin.dao.find(sqlPara2);
				int lastVote = 0;
				int position = 1;
				for (TpJoin tpJoin : items) {
					tpJoin.setPosition(position);
					int currentVote = tpJoin.getVote();
					if (position == 1) {
						tpJoin.setNextVote(0);
					} else {
						int nextVote = lastVote - currentVote;
						tpJoin.setNextVote(nextVote);
					}
					lastVote = currentVote;
					tpJoin.update();
					position++;
				}
				return true;
			}
		});
		if (!flag) {
			LogKit.error("Bill push error " + orderNo);
		}
	}

}
